package pers.cocoadel.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import pers.cocoadel.springcloud.entities.CommonResult;
import pers.cocoadel.springcloud.entities.Payment;

import java.util.HashMap;

@RestController
public class PaymentController
{

    @Value("${server.port}")
    private String serverPort;

    private static HashMap<Integer, Payment> paymentMap = new HashMap<>();

    static
    {
        paymentMap.put(0, new Payment(0L, "ruby"));
        paymentMap.put(1, new Payment(1L, "weiss"));
        paymentMap.put(2, new Payment(2L, "yang"));
        paymentMap.put(3, new Payment(3L, "black"));
    }


    @GetMapping("/payment/paymentSql/{id}")
    @SentinelResource(value = "payment/paymentSql/id",
            blockHandler = "blockHandler",
            exceptionsToIgnore = IllegalArgumentException.class)
    public CommonResult<Payment> paymentSql(@PathVariable("id") Integer id)
    {
        if (id < 4 && id >= 0)
        {
            Payment payment = paymentMap.get(id);
            return new CommonResult<>(200, "OK server port " + serverPort, payment);
        }
        else if (id == 4)
        {
            throw new IllegalArgumentException("");
        }
        else
        {
            throw new NullPointerException();
        }
    }

    public CommonResult<Payment> blockHandler(Integer id, BlockException ex)
    {
        return new CommonResult<>(444,"服务器异常！/(ㄒoㄒ)/~~" + ex.getMessage(),null);
    }
}
